/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.apache.skywalking.apm.plugin.spring.mvc.commons;

import com.alibaba.fastjson.JSON;
import com.ctrip.framework.apollo.ConfigService;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.util.CollectionUtil;
import org.apache.skywalking.apm.util.StringUtil;
import org.springframework.http.server.reactive.ServerHttpRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

public class RequestUtil {
    public static void collectHttpParam(HttpServletRequest request, AbstractSpan span) {
//        final Map<String, String[]> parameterMap = request.getParameterMap();
        String queryString = request.getQueryString();
        if (StringUtil.isNotBlank(queryString)) {
            Tags.HTTP.PARAMS.set(span, queryString);
        }
    }

//    public static void collectHttpParam(jakarta.servlet.http.HttpServletRequest request, AbstractSpan span) {
//        final Map<String, String[]> parameterMap = request.getParameterMap();
//        if (parameterMap != null && !parameterMap.isEmpty()) {
//            String tagValue = CollectionUtil.toString(parameterMap);
//            tagValue = SpringMVCPluginConfig.Plugin.Http.HTTP_PARAMS_LENGTH_THRESHOLD > 0 ?
//                    StringUtil.cut(tagValue, SpringMVCPluginConfig.Plugin.Http.HTTP_PARAMS_LENGTH_THRESHOLD) : tagValue;
//            Tags.HTTP.PARAMS.set(span, tagValue);
//        }
//    }

    public static void collectHttpParam(ServerHttpRequest request, AbstractSpan span) {
        Map<String, String[]> parameterMap = new HashMap<>(request.getQueryParams().size());
        request.getQueryParams().forEach((key, value) -> {
            parameterMap.put(key, value.toArray(new String[0]));
        });
        if (!parameterMap.isEmpty()) {
            String tagValue = CollectionUtil.toString(parameterMap);
            tagValue = SpringMVCPluginConfig.Plugin.Http.HTTP_PARAMS_LENGTH_THRESHOLD > 0 ?
                    StringUtil.cut(tagValue, SpringMVCPluginConfig.Plugin.Http.HTTP_PARAMS_LENGTH_THRESHOLD) : tagValue;
            Tags.HTTP.PARAMS.set(span, tagValue);
        }
    }

    public static void collectHttpHeaders(HttpServletRequest request, AbstractSpan span, String[] neededHeaders) {
        final List<String> headersList = new ArrayList<>(neededHeaders.length);
        Arrays.stream(neededHeaders)
                .filter(
                        headerName -> request.getHeaders(headerName) != null)
                .forEach(headerName -> {
                    Enumeration<String> headerValues = request.getHeaders(
                            headerName);
                    List<String> valueList = Collections.list(
                            headerValues);
                    if (!CollectionUtil.isEmpty(valueList)) {
                        String headerValue = valueList.toString();
                        headersList.add(headerName + "=" + headerValue);
                    }
                });
        collectHttpHeaders(headersList, span);
    }

//    public static void collectHttpHeaders(jakarta.servlet.http.HttpServletRequest request, AbstractSpan span) {
//        final List<String> headersList = new ArrayList<>(SpringMVCPluginConfig.Plugin.Http.INCLUDE_HTTP_HEADERS.size());
//        SpringMVCPluginConfig.Plugin.Http.INCLUDE_HTTP_HEADERS.stream()
//                .filter(
//                        headerName -> request.getHeaders(headerName) != null)
//                .forEach(headerName -> {
//                    Enumeration<String> headerValues = request.getHeaders(
//                            headerName);
//                    List<String> valueList = Collections.list(
//                            headerValues);
//                    if (!CollectionUtil.isEmpty(valueList)) {
//                        String headerValue = valueList.toString();
//                        headersList.add(headerName + "=" + headerValue);
//                    }
//                });
//
//        collectHttpHeaders(headersList, span);
//    }

    public static void collectHttpHeaders(ServerHttpRequest request, AbstractSpan span) {
        final List<String> headersList = new ArrayList<>(SpringMVCPluginConfig.Plugin.Http.INCLUDE_HTTP_HEADERS.size());
        SpringMVCPluginConfig.Plugin.Http.INCLUDE_HTTP_HEADERS.stream()
                .filter(headerName -> getHeaders(request, headerName).hasMoreElements())
                .forEach(headerName -> {
                    Enumeration<String> headerValues = getHeaders(request, headerName);
                    List<String> valueList = Collections.list(
                            headerValues);
                    if (!CollectionUtil.isEmpty(valueList)) {
                        String headerValue = valueList.toString();
                        headersList.add(headerName + "=" + headerValue);
                    }
                });

        collectHttpHeaders(headersList, span);
    }

    private static void collectHttpHeaders(final List<String> headersList, final AbstractSpan span) {
        if (headersList != null && !headersList.isEmpty()) {
            String tagValue = String.join("\n", headersList);
            tagValue = SpringMVCPluginConfig.Plugin.Http.HTTP_HEADERS_LENGTH_THRESHOLD > 0 ?
                    StringUtil.cut(tagValue, SpringMVCPluginConfig.Plugin.Http.HTTP_HEADERS_LENGTH_THRESHOLD) : tagValue;
            Tags.HTTP.HEADERS.set(span, tagValue);
        }
    }

    public static Enumeration<String> getHeaders(final ServerHttpRequest request, final String headerName) {
        List<String> values = request.getHeaders().get(headerName);
        if (values == null) {
            return Collections.enumeration(Collections.emptyList());
        }
        return Collections.enumeration(values);
    }

    /**
     * 采集请求体
     * todo: 配置开关动态配置 (开启,长度限制)
     */
    public static void collectHttpBody(HttpServletRequest httpServletRequest, Object[] allArguments, AbstractSpan span) {
        try {
            if (allArguments != null && allArguments.length > 0) {
                List<String> params = httpServletRequest.getParameterMap().values().stream().flatMap(Arrays::stream).collect(Collectors.toList());
                Object o = Arrays.stream(allArguments).filter(s -> {
                    return !params.contains(s) && !(s instanceof HttpServletRequest);
                }).limit(1).findAny().get();
                if (o != null) {
                    String jsonString = JSON.toJSONString(allArguments[0]);
                    Tags.HTTP.BODY.set(span, jsonString);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final ILog LOGGER = LogManager.getLogger(RequestUtil.class);
    /**
     * 采集响应(是否)
     */
    public static void collectHttpResponse(Object ret, AbstractSpan span) {
        LOGGER.debug("准备采集http响应");
        Boolean on = ConfigService.getAppConfig().getBooleanProperty("skywalking.agent.switch.collect.mvc.response", true);
        LOGGER.debug("配置中心开关on={}", on);
        if (on) {
            try {
                if (ret != null) {
                    if (ret instanceof String) {
                        Tags.HTTP.RESPONSE.set(span, ret.toString());
                    } else {
                        String jsonString = JSON.toJSONString(ret);
                        Tags.HTTP.RESPONSE.set(span, jsonString);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
